package com.ck.shardingspheremaster.algorithm;

/**
 * @Author yd
 * @Date 2018/12/28 22:14
 */


import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;


public class DatabaseShardingAlgorithm implements PreciseShardingAlgorithm<String> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<String> preciseShardingValue) {

        String db_name="db_";
        try {
            Date date = (Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(preciseShardingValue.getValue());

            String year = String.format("%tY", date);
            String mon  = String.format("%tm",date);
            db_name=db_name+year+mon;
            System.out.println("db_name:" + db_name);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        for (String each : collection) {
            System.out.println("db:" + each);
            if (each.equals(db_name)) {
                return each;
            }
        }

        throw new IllegalArgumentException();
    }
}
